from stark.service.stark import StarkConfig, Option, get_choice_text
from django import forms
from crm_app import models
from django.db import transaction
from django.shortcuts import HttpResponse, reverse
from django.conf import settings
from django.utils.safestring import mark_safe
from crm_app.permission.base import BASERbacPermission


class CustomerConfig(BASERbacPermission, StarkConfig):
    def display_follow(self, row=None, header=False):
        if header:
            return "跟进记录"

        url = reverse("stark:crm_app_consultrecord_changelist")
        return mark_safe('<a href="%s?cid=%s">跟进记录</a>' % (url, row.pk))

    list_display = [
        "name",
        "qq",
        get_choice_text("status", "状态"),
        get_choice_text("gender", "性别"),
        get_choice_text("source", "来源"),
        display_follow,
    ]
    order_by = ['-id']
    search_list = ["name"]
    list_filter = [
        Option("status", is_choices=True, text_func=lambda x: x[1]),
        Option("gender", is_choices=True, text_func=lambda x: x[1]),
        Option("source", is_choices=True, text_func=lambda x: x[1]),
    ]


class PublicModelForm(forms.ModelForm):
    class Meta:
        model = models.Customer
        exclude = ["status", "consultant"]


class PublicCustomerConfig(BASERbacPermission, StarkConfig):
    list_display = [
        "name",
        "qq",
        get_choice_text("status", "状态"),
        get_choice_text("gender", "性别"),
        get_choice_text("source", "来源"),
    ]
    order_by = ['-id']
    search_list = ["name"]
    list_filter = [
        Option("status", is_choices=True, text_func=lambda x: x[1]),
        Option("gender", is_choices=True, text_func=lambda x: x[1]),
        Option("source", is_choices=True, text_func=lambda x: x[1]),
    ]

    model_form_class = PublicModelForm

    def multi_apply(self, request):
        """
        批量申请私户
        :return:
        """
        id_list = request.POST.getlist("pk")
        current_user_id = 1  # 以后要改成当前登录用户的id

        my_customer_count = models.Customer.objects.filter(consultant_id=current_user_id, status=2).count()

        if my_customer_count + len(id_list) > settings.MAX_PRIVATE_CUSTOMER_COUNT:
            return HttpResponse("别贪多，你已经申请到顶额了")

        flag = False
        with transaction.atomic():
            origin_queryset = models.Customer.objects.filter(id__in=id_list, consultant__isnull=True).select_for_update()
            if len(origin_queryset) == len(id_list):
                models.Customer.objects.filter(id__in=id_list).update(consultant_id=current_user_id)
                flag = True

        if not flag:
            return HttpResponse("你来晚了，此客户已经被别人申请了")

    multi_apply.text = "批量申请"

    action_list = [multi_apply]

    def get_queryset(self):
        # 显示所有公户
        return self.model_class.objects.filter(consultant__isnull=True)

    def get_list_display(self):
        val = super().get_list_display()
        val.remove(StarkConfig.display_del)  # 默认公户不显示删除操作
        val.insert(0, StarkConfig.display_checkbox)
        return val


class PrivateModelForm(forms.ModelForm):
    class Meta:
        model = models.Customer
        exclude = ["status", "consultant"]


class PrivateCustomerConfig(BASERbacPermission, StarkConfig):
    def display_follow(self, row=None, header=False):
        if header:
            return "跟进记录"

        url = reverse("stark:crm_app_consultrecord_pri_changelist")
        return mark_safe('<a href="%s?cid=%s">跟进记录</a>' % (url, row.pk))

    list_display = [
        "name",
        "qq",
        get_choice_text("status", "状态"),
        get_choice_text("gender", "性别"),
        get_choice_text("source", "来源"),
        display_follow,
    ]
    order_by = ['-id']
    search_list = ["name"]
    list_filter = [
        Option("status", is_choices=True, text_func=lambda x: x[1]),
        Option("gender", is_choices=True, text_func=lambda x: x[1]),
        Option("source", is_choices=True, text_func=lambda x: x[1]),
    ]
    model_form_class = PrivateModelForm

    def multi_remove(self, request):
        """
        批量移除私户
        :return:
        """
        id_list = request.POST.getlist("pk")
        current_user_id = 1  # 以后要改成当前登录用户的id
        models.Customer.objects.filter(id__in=id_list, status=2, consultant_id=current_user_id).update(consultant=None)

    multi_remove.text = "批量移除"

    action_list = [multi_remove]

    def get_queryset(self):
        # 显示当前销售的私户
        current_user_id = 1  # 以后要改成当前登录用户的id
        return self.model_class.objects.filter(consultant_id=current_user_id)

    def save(self, form, modify=False):
        current_user_id = 1  # 以后要改成当前登录用户的id
        form.instance.consultant = models.UserInfo.objects.get(id=current_user_id)
        form.save()

    # 根据list_display中的内容显示
    def get_list_display(self):
        val = super().get_list_display()
        val.remove(StarkConfig.display_del)  # 默认私户不显示删除操作
        val.insert(0, StarkConfig.display_checkbox)
        return val
